<template>
  <div class="app-container">
    <el-row :gutter="20" style="height:calc(100% - 40px);">
      <el-col :span="4" style="height: 500px; overflow-y:auto;">
        <div class="head-container" v-loading="loading">
            <el-tree-select
              v-model="selectedUnitId"
              :data="UnitOptions"
              default-expand-all
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="选择单位"
              check-strictly
              @node-click="handleNodeClickUnit"
          />
        </div>
        <el-divider />
        <div class="head-container" v-loading="loadingdeptOptions">
            <el-tree :data="deptOptions" 
            :props="{ value: 'id', label: 'label', children: 'children' }"
            :expand-on-click-node="false" 
            :filter-node-method="filterNode" 
            ref="deptTreeRef" node-key="id"
            highlight-current
            @node-click="handleNodeClick" />
        </div>
    </el-col>
    <el-col :span="17">
      <el-row :gutter="1"  style="height:100%">
        <el-col :span="12" style="height:50%;margin-bottom: 1px;" @click="PlayClick(0)">
          <div id="Player0" :style="getPlayerStyle(0)"></div>
        </el-col>
        <el-col :span="12" style="height:50%;margin-bottom: 1px;" @click="PlayClick(1)">
          <div id="Player1" :style="getPlayerStyle(1)"></div>
        </el-col>
        <el-col :span="12" style="height:50%;margin-bottom: 1px;" @click="PlayClick(2)">
          <div id="Player2" :style="getPlayerStyle(2)"></div>
        </el-col>
        <el-col :span="12" style="height:50%;margin-bottom: 1px;" @click="PlayClick(3)">
          <div id="Player3" :style="getPlayerStyle(3)"></div>
        </el-col>
      </el-row>
    </el-col>
    <el-col :span="3" style="display: flex;display: -webkit-flex;flex-direction: column;">
      <el-button @click="closevideo" class="mb-4">关闭监控</el-button>
    </el-col>
  </el-row>
  
  </div>
</template>
<script>
 import { ElMessage } from 'element-plus'
 import { getunitDeviceChannelTreeType } from "@/api/ParameterSetting/Device";
 import { getChannelUrl,} from "@/api/videoApi/videoApi";
 import {deptTreeSelectPost} from "@/api/system/user.js";
export default {
  data() {
    return {
      form:{
      },
      params:{
        unitId:'',
        bigType: "自侦办案区"
      },
      playIndex:0,
      loading:false,
      loadingdeptOptions:false,
      activePlayer:0,
      player0: '',
      player1: '',
      player2: '',
      player3: '',
      selectedUnitId:'',
      UnitOptions:[],
      deptOptions:[],
      urlList:[],
      deptName:'',
    }
  },
  created(){
    
  },
  mounted() {
    // 实例化播放器
    this.player0 = new WasmPlayer(null, 'Player0', )
    this.player1 = new WasmPlayer(null, 'Player1', )
    this.player2 = new WasmPlayer(null, 'Player2', )
    this.player3 = new WasmPlayer(null, 'Player3', )
    this.getDeptTree()
  },
  computed: {
   
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      this.loading = true
      deptTreeSelectPost({isUnit: true}).then(res => {
        this.UnitOptions  = res.data
        this.loading = false
      });
    },
    
    callbackfun(e) {
    },

    playvideo() {
      switch (this.playIndex) {
        case 0:
          this.player0.stop()
          this.player0.play(this.urlList[0], 1);
          this.playIndex = 1
          this.activePlayer = 1
          break;
        case 1:
          this.player1.stop()
          this.player1.play(this.urlList[1], 1);
          this.playIndex = 2
          this.activePlayer = 2
          break;
        case 2:
          this.player2.stop()
          this.player2.play(this.urlList[2], 1);
          this.playIndex = 3
          this.activePlayer = 3
          break;
        case 3:
          this.player3.stop()
          this.player3.play(this.urlList[3], 1);
          this.playIndex = 0
          this.activePlayer = 0
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
    }
,
closevideo() {
      switch (this.playIndex) {
        case 0:
          this.player0.destroy()
          this.player0.url = ''
          this.urlList[this.playIndex] = ''
          this.player0 = new WasmPlayer(null, 'Player0', )
          break;
        case 1:
          this.player1.destroy()
          this.player1.url = ''
          this.urlList[this.playIndex] = ''
          this.player1 = new WasmPlayer(null, 'Player1', )
          break;
        case 2:
          this.player2.destroy()
          this.player2.url = ''
          this.urlList[this.playIndex] = ''
          this.player2 = new WasmPlayer(null, 'Player2', )
          break;
        case 3:
          this.player3.destroy()
          this.player3.url = ''
          this.urlList[this.playIndex] = ''
          this.player3 = new WasmPlayer(null, 'Player3', )
          break;
        default:
          ElMessage.error('播放器索引无效');
      }
    },
    PlayClick(index){
      console.log(this)
      // switch (index) {
      //   case 0:
      //     break;
      //   case 1:
      //     break;
      //   case 2:
      //     break;
      //   case 3:
      //     break;
      //   default:
      //     ElMessage.error('播放器索引无效');
      // }
      this.playIndex = index
      this.activePlayer = index;
    },
    getPlayerStyle(index) {
      // 如果当前播放器是选中的播放器，返回带边框的样式，否则返回空样式
      return this.activePlayer == index
        ? { border: '2px solid red' } // 选中的播放器添加红色边框
        : {};
    },
    filterNode(value, data){
      if (!value) return true;
      return data.deptName.indexOf(value) !== -1;
    },
    handleNodeClickUnit(data){
      this.form.bxcunitId = data.id
      this.getunitDeviceChannelTreeTypeList(data.id)
    },
    handleNodeClick(data) {
      // 处理节点单击事件
        if(data.channelcode){
          const playerQuery = {
            deviceId:data.channelcode,
            channel:data.channels,
            monitorServerId:data.monitorserverId,
          }
        getChannelUrl(playerQuery).then(res => {
            var mergeUrl = res.data.prefix + res.data.EasyDarwin.Body.URL
            this.urlList[this.playIndex] = mergeUrl
            this.playvideo()
        })
      }
    },

    getunitDeviceChannelTreeTypeList(UnitId) {
      this.loadingdeptOptions = true
      this.deptOptions = []
      this.params.unitId = UnitId 
      getunitDeviceChannelTreeType(this.params).then(res => {
        // 递归转换 roomTypes 中的结构
        const transformRoomTypes = (roomTypes) => {
          return roomTypes.map(room => {
            // 保留原有的 id 和 label，如果存在的话
            const transformedRoom = {
              ...room,
              label: room.label || room.roomname,  // 仅当 label 不存在时才使用 roomname
              id: room.id || room.roomId          // 仅当 id 不存在时才使用 roomId
            };

            if (room.baseMonitorChannels) {
              // 将 baseMonitorChannels 改为 children，并处理其中的字段
              transformedRoom.children = room.baseMonitorChannels.map(channel => {
                return {
                  ...channel,
                  label: channel.label || channel.channelname, // 仅当 label 不存在时才使用 channelname
                  id: channel.id || channel.channelcode       // 仅当 id 不存在时才使用 channelcode
                };
              });
              delete transformedRoom.baseMonitorChannels; // 删除 baseMonitorChannels 字段
            }
            // 递归处理嵌套的 children（即 room 下的子房间）
            if (room.children && room.children.length > 0) {
              transformedRoom.children = transformRoomTypes(room.children);
            }
            return transformedRoom;
          });
        };
        if (res.data && Array.isArray(res.data) && res.data[0] && res.data[0].roomTypes) {
            var roomTypesdata = transformRoomTypes(res.data[0].roomTypes);
        } else {
            ElMessage.error('当前单位无监控节点');
            this.loadingdeptOptions = false
        }
        // 处理 videoTypes
        if (res.data && res.data[0] && res.data[0].videoTypes) {
            let videoTypesdata = res.data[0].videoTypes;
            videoTypesdata.forEach(videoType => {
                videoType.children.forEach(channel => {
                    channel.label = channel.label || channel.channelname; // 使用 channelname 作为备选
                    channel.id = channel.monitorchannelsId || channel.channelcode; // 使用 channelcode 作为备选
                });
            });
            this.deptOptions = [
              ...roomTypesdata,
              ...videoTypesdata
            ];
        } else {
            console.error("videoTypes data is missing in the response:", res.data);
        }
        this.loadingdeptOptions = false
      });
    },

  }  
}
</script>
<style scoped>
.app-container { height: calc(100vh - 84px);width: 100%; }
.el-button+.el-button{margin-left: 0;}
.player-content{height: 100%;}
</style>